/*
 * @Author: szx
 * @Date: 2022-05-04 15:22:41
 * @LastEditTime: 2022-05-04 15:26:56
 * @Description:
 * @FilePath: \leetcode\100-199\127\127.js
 */
var ladderLength = function (beginWord, endWord, wordList) {
    const wordSet = new Set(wordList);
    if (!wordSet.has(endWord)) return 0;
    let begSet = [beginWord],
        endSet = [endWord],
        n = 1;
    while (begSet.length > 0) {
        const nextBegins = [];
        if (begSet.length > endSet.length) [begSet, endSet] = [endSet, begSet];

        for (let k = 0; k < begSet.length; k++) {
            let m = begSet[k];
            for (let i = 0; i < m.length; i++) {
                for (let c = 97; c <= 122; c++) {
                    let newm = m.slice(0, i) + String.fromCharCode(c) + m.slice(i + 1);
                    if (endSet.includes(newm)) {
                        return n + 1;
                    }
                    if (wordSet.has(newm)) {
                        nextBegins.push(newm);
                        wordSet.delete(newm);
                    }
                }
            }
        }
        begSet = nextBegins;
        n++;
    }
    return 0;
};
